// 获取pages.json
import pagesJson from '@/pages.json';
import store from '@/store';

// 主包路径
const routes = pagesJson.pages
// 分包路径
const subPackages = pagesJson.subPackages || []
// 解析分包路径
subPackages.forEach((item, index) => {
	item.pages.forEach((v, k) => {
		// 拼接分包路径
		v.path = item.root + '/' + v.path
		routes.push(v);
	})
})

export default {
	install(Vue) {
		/**
		 * @desc 普通跳转
		 * @param path  跳转路径
		 */
		Vue.prototype.$navigateTo = function(path = '') {
			router(path);
		}
		/**
		 * @desc 跳转tab面
		 * @param path  跳转路径
		 */
		Vue.prototype.$switchTab = function(path) {
			if (store.state.init.systemConfig.index_agent_show == 1) {
				switch (path) {
					case '/pages/index/index':
						store.commit('tabbar/setCurrent', 0);
						break;
					case '/pages/category/index':
						store.commit('tabbar/setCurrent', 1);
						break;
					case '/pages/agent/index':
						store.commit('tabbar/setCurrent', 2);
						break;
					case '/pages/shopCart/index':
						store.commit('tabbar/setCurrent', 3);
						break;
					default:
						store.commit('tabbar/setCurrent', 4);
						break;
				}
			} else {
				switch (path) {
					case '/pages/index/index':
						store.commit('tabbar/setCurrent', 0);
						break;
					case '/pages/category/index':
						store.commit('tabbar/setCurrent', 1);
						break;
					case '/pages/shopCart/index':
						store.commit('tabbar/setCurrent', 2);
						break;
					default:
						store.commit('tabbar/setCurrent', 3);
						break;
				}
			}
			console.log(store.state.init.systemConfig.index_agent_show);
			router(path, 'switchTab');
		}
		/**
		 * @desc 关闭当前页，跳转
		 * @param path  跳转路径
		 */
		Vue.prototype.$redirectTo = function(path) {
			router(path, 'redirectTo');
		}
		/**
		 * @desc 关闭所有页，跳转
		 * @param path  跳转路径
		 */
		Vue.prototype.$reLaunch = function(path) {
			router(path, 'reLaunch');
		}
		/**
		 * @desc 返回上一页
		 * @param path  跳转路径
		 */
		Vue.prototype.$toBack = function(delta = 1) {
			uni.navigateBack({
				delta: delta,
			})
		}
		/**
		 * @desc 跳转验证
		 * @param path  跳转路径
		 * @param type  跳转方式
		 */
		const router = function(path = '', type = 'navigateTo') {
			const pathArr = path.split('?');
			if (!Vue.prototype.$isLogin()) { // 未登陆
				// 在路由菜单中找到要去的页面
				const route = routes.find(item => '/' + item.path === pathArr[0])
				if (path == '' || route != undefined) {
					if (path == '' || route.needLogin === undefined || route.needLogin) { // 当前页面免登录
						// 去登陆
						Vue.prototype.$toLogin();
						return false;
					}
				}
			}
			// 跳转该页面
			uni[type]({
				url: path
			})
		}
	}
}